package com.leo.auth.handler;

import cn.hutool.json.JSONUtil;
import com.leo.common.core.enums.ExceptionCodeEnum;
import com.leo.common.core.model.Result;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 登录失败处理逻辑
 * </p>
 *
 * @author ：Leo
 * @since ：2021-04-08 13:52
 */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
        //返回json数据
        Result<Void> result;
        if (e instanceof AccountExpiredException) {
            //账号过期
            result = Result.error(ExceptionCodeEnum.AUTH_USER_EXPIRED);
        } else if (e instanceof BadCredentialsException) {
            //密码错误
            result = Result.error(ExceptionCodeEnum.AUTH_BAD_PWD);
        } else if (e instanceof CredentialsExpiredException) {
            //密码过期
            result = Result.error(ExceptionCodeEnum.AUTH_CREDENTIAL_EXPIRED);
        } else if (e instanceof DisabledException) {
            //账号不可用
            result = Result.error(ExceptionCodeEnum.AUTH_ACCOUNT_DISABLED);
        } else if (e instanceof LockedException) {
            //账号锁定
            result = Result.error(ExceptionCodeEnum.AUTH_USER_LOCKED);
        } else if (e instanceof InternalAuthenticationServiceException) {
            //用户不存在
            result = Result.error(ExceptionCodeEnum.AUTH_USER_NAME_NOT_FOUND);
        }else{
            //其他错误
            result = Result.error(ExceptionCodeEnum.AUTH_EXCEPTION);
        }
        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台
        httpServletResponse.getWriter().write(JSONUtil.toJsonStr(result));
    }
}
